# -*- coding: utf-8 -*-
# @Time    : 2025/6/28 13:46
# @Author  : Alvin
# @File    : JlSyncOrderSignTask.py
# @Des     : 晋良抖音预约-->提货-->签收
import logging
import logging.handlers
import logging.handlers
import os
import time

from handler.JlSignImpl import JlSignImpl
from utils import CommonUtil
from utils.DatabaseHandler import DatabaseHandler


def init_logging():
    """
    日志文件设置
    """
    if not os.path.exists("log"):
        os.makedirs("log")
    logger = logging.getLogger()
    logger.setLevel(20)

    sh = logging.StreamHandler()
    current_path = os.path.dirname(__file__)
    log_file = f"{current_path}/log/sign_task.log"
    file_log = logging.handlers.TimedRotatingFileHandler(log_file, 'MIDNIGHT', 1, 15)
    formatter = logging.Formatter('[%(asctime)s] [%(levelname)-7s] [%(module)s:%(filename)s-%(funcName)s-%(lineno)d] %(message)s')
    sh.setFormatter(formatter)
    file_log.setFormatter(formatter)

    logger.addHandler(sh)
    logger.addHandler(file_log)

    logging.info("Current log level is : %s", logging.getLevelName(logger.getEffectiveLevel()))


class JlSyncOrderSignTask:

    def __init__(self):
        self.chunk_size = 1000
        self.max_workers = 9
        self.log_text = "同步单签收任务"

    def excute_sync_order_sign(self):
        logging.info(f"----------------------------------------{self.log_text} start---------------------------------------")
        logging.info(f"【{self.log_text}】开始时间:%s", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
        dbDataList = DatabaseHandler().get_sync_order_sign_list()
        if dbDataList is None or len(dbDataList) <= 0:
            logging.info(f"{self.log_text}任务数量为0，任务结束")
            return
        all_data_list = CommonUtil.splitList(dbDataList, self.chunk_size)
        logging.info(f"{self.log_text}数据库查询结束,共获取 {len(dbDataList)} 条数据，划分为 {len(all_data_list)} 个分块")

        for index, data_list in enumerate(all_data_list):
            batch_index = index + 1
            logging.info(f"开始第：{batch_index}/{len(all_data_list)}次任务")
            impl = JlSignImpl()
            impl.start_handle_sign_task(batch_index, data_list)

        logging.info(f"【{self.log_text}】任务结束时间:%s", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
        logging.info(f"----------------------------------------{self.log_text} all end---------------------------------------")


if __name__ == '__main__':
    init_logging()
    signTask = JlSyncOrderSignTask()
    signTask.excute_sync_order_sign()
